const moment = require('moment');
const jwt = require('jsonwebtoken');
const utilTool = require('../../util');
const $config = require('../../config');

module.exports = {
  updateUser: async (ctx, next) => {
    $config.documents = 'site' // 切换文档集合
    const token = ctx.request.header.token;
    await jwt.verify(token, $config.tokenSecret, async (err, resultToken) => { // resultToken 解析token值
      if (err) {  //  时间失效的时候/ 伪造的token
        ctx.body = {
          success: false,
          result: '验证已过期！',
          ...err
        };
        return;
      }
      const param = ctx.request.body;
      const ObjectID = require('mongodb').ObjectID;
      const updateParam = {}
      let noUsername = true
      const resultData = {
        success: false,
        result: null
      };
      for (let i in param) {
        if (i !== 'id') updateParam[i] = param[i] // 屏蔽_id标记
        if (i === 'passWord') updateParam[i] = await utilTool.md5(param[i])
        if (i === 'access') {
          Array.isArray(param[i])
            ? updateParam[i] = param[i]
            : updateParam[i] = param[i].split(',')
        }
      }
      // 判断用户是否重复
      let nameResult = ''
      if (updateParam['userName']) {
        nameResult = await utilTool.find({userName: updateParam['userName']}, {_id: 0, userName: 1});
        if (nameResult.length > 0) {
          if (nameResult[0].userName === updateParam['userName']) {
            resultData.success = false
            resultData.result = '姓名不能重复！'
            noUsername = false
          }
        }
      }
      // 修改用户数据
      if (noUsername) {
        const data = await utilTool.updateOne({_id: ObjectID(param.id)}, updateParam);
        resultData.success = true
        resultData.result = data
      }
      ctx.body = resultData;
    })
  }
};
